import { QueryKey, useQueryClient } from "react-query";

export const useConfig = (queryKey: QueryKey, callback: (target: any, old?: any) => any) => {
    const queryClient = useQueryClient();
    return {
        onSuccess: () => queryClient.invalidateQueries(queryKey),
        async onMutate(target) {
            // 保存修改前的数据 用于数据回滚
            const previousItems = queryClient.getQueryData(queryKey);
            queryClient.setQueryData(queryKey, (old) => {
                return callback(target, old)
            })
            return { previousItems }
        },
        // 如果执行报错，就回滚到之前的数据
        onError: (error: any, newItem: any, context) => {
            queryClient.setQueryData(queryKey, (context as { previousItems: any }).previousItems)
        }

    }
}

export const useDeleteConfig = (queryKey) => useConfig(queryKey, (target, old) => old?.filter(item => item.id !== target.id) || [])
export const useEditConfig = (queryKey) => useConfig(queryKey, (target, old) => old?.map(item => item.id === target.id ? { ...item, ...target } : item) || [])
export const useAddConfig = (queryKey) => useConfig(queryKey, (target, old) => old ? [...old, target] : [])
